package pl.edu.pw.perg.compinfodb.command;

import java.util.LinkedList;
import java.util.List;

import org.springframework.richclient.command.support.AbstractActionCommandExecutor;

import pl.edu.pw.perg.compinfodb.datamodel.IConditionChangeListener;
import pl.edu.pw.perg.compinfodb.datamodel.IPhysicalElementSelectionListener;
import pl.edu.pw.perg.compinfodb.datamodel.IRefreshListener;
import pl.edu.pw.perg.compinfodb.datamodel.ModulesHistoryTableModel;
import pl.edu.pw.perg.compinfodb.datamodel.StructureHistoryTableModel;
import pl.edu.pw.perg.compinfodb.entities.PhysicalElement;
import pl.edu.pw.perg.compinfodb.entities.VirtualElement;
import pl.edu.pw.perg.compinfodb.manager.IPhysicalElementManager;

public class EjectElementCommandExecutor extends AbstractActionCommandExecutor implements IPhysicalElementSelectionListener, IConditionChangeListener {

	private PhysicalElement pe;
	private IPhysicalElementManager physicalElementManager;
//	private IVirtualElementManager virtualElementManager;
	private List<IRefreshListener> refreshListeners = new LinkedList<IRefreshListener>();
	private StructureHistoryTableModel structureHistory;
	private ModulesHistoryTableModel modulesHistory;
	
	@Override
	public void execute() {
		VirtualElement ve = pe.getVirtualElement();
//		PhysicalElement pe = (PhysicalElement) ve.getPhysicalElement();
		pe.setVirtualElement(null);
//		ve.setPhysicalElement(null);
		
//		virtualElementManager.merge(ve);
		physicalElementManager.merge(pe);
		for (IRefreshListener l : refreshListeners) {
			l.refresh();
		}
		setEnabled(false);
		structureHistory.ejected(pe);
		modulesHistory.ejected(ve, pe);
	}

//	public void setVe(VirtualElement ve) {
//		this.ve = ve;
//	}

	public void setPhysicalElementManager(
			IPhysicalElementManager physicalElementManager) {
		this.physicalElementManager = physicalElementManager;
	}

//	public void setVirtualElementManager(
//			IVirtualElementManager virtualElementManager) {
//		this.virtualElementManager = virtualElementManager;
//	}

//	public void selectionChanged(VirtualElement ve) {
//		this.ve = ve;
//		if(ve != null && ve.getPhysicalElement() != null)
//			setEnabled(true);
//		else
//			setEnabled(false);
//		
//	}

	public void conditionChanged(boolean conditionValue) {
		setEnabled(conditionValue);		
	}

	public void selectionChanged(PhysicalElement ce) {
		this.pe = ce;
		
	}
	
	public void addRefreshListener(IRefreshListener l){
		refreshListeners.add(l);
	}

	public void setStructureHistory(StructureHistoryTableModel structureHistory) {
		this.structureHistory = structureHistory;
	}

	public void setModulesHistory(ModulesHistoryTableModel modulesHistory) {
		this.modulesHistory = modulesHistory;
	}
}
